package com.xsy.req.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 功能描述：获取销售易信息工具类
 */
@Component
public class CrmApiUtils {
    private final static Logger logger = LoggerFactory.getLogger(CrmApiUtils.class);
    @Value("${xsy.userName}")
    private static String username = "13918056203";
    @Value("${xsy.password}")
    private static String password = "Getech2023";
    @Value("${xsy.securityCode}")
    private static String securityCode = "n5vrAAII";
    @Value("${xsy.clientId}")
    private static String clientId = "48d0cc503b721322e4e618b87b9f81a8";
    @Value("${xsy.clientSecret}")
    private static String clientSecret = "ea1a5bd9e522965a5d829c867ac8a9b8";
    @Value("${xsy.domain}")
    private static String domain = "https://api-p05.xiaoshouyi.com";
    private static String LOGIN_URL = "https://login.xiaoshouyi.com/auc/oauth2/token"; // 获取销售易token接口

    private static Cache cacheApi;

    static {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
        cacheApi = cacheManager.getCache("default");
    }

    public static void main(String[] args) throws IOException {
        getToken();
    }

    public static ResultVo uploadFiles(List<JSONObject> fileList) {
        try {
            // 目标上传URL
            String url = domain + "/rest/file/v2.0/file/batch";

            // 创建HttpClient实例
            HttpClient httpClient = HttpClients.createDefault();

            // 创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Authorization", "Bearer " + getToken());

            // 使用MultipartEntityBuilder构建上传的 multipart form data
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.RFC6532);
            builder.addTextBody("needFileId", "true");
            for (JSONObject file : fileList) {
                builder.addBinaryBody("files", getFileByteByUrl(file.getString("fileUrl")), ContentType.DEFAULT_BINARY, file.getString("fileName"));
            }
            httpPost.setEntity(builder.build());

            // 执行上传
            HttpResponse response = httpClient.execute(httpPost);

            // 打印响应状态
            System.out.println("Response Status: " + response.getStatusLine().getStatusCode());
            JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            if (!Objects.equals(result.getInteger("code"), 200)) {
                return ResultVo.error("上传文件异常");
            }

            // 打印响应内容
            System.out.println("Response Body: " + result);
            List<JSONObject> tempList = JSONArray.parseArray(result.getString("result"), JSONObject.class);
            String fileIds = tempList.stream().map(v -> v.getString("fileId")).collect(Collectors.joining(","));
            return ResultVo.success(fileIds);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(e.getMessage());
        }
    }

    /**
     * 通过url方式获取文件流
     * @param urlPath
     * @return
     */
    public static byte[] getFileByteByUrl(String urlPath) {
        try (
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                InputStream inputStream = new URL(urlPath).openStream())
        {
            byte[] buffer = new byte[1024 * 4];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getToken() throws IOException {
        JSONObject tokenInfo = cacheApi.get("tokenInfo", JSONObject.class);
        if (tokenInfo != null) {
            String token = tokenInfo.getString("access_token");
            return token;
        }
        logger.info("没有缓存token，开始查询销售易token  =======> ");
        String url = "%s?grant_type=password&client_id=%s&client_secret=%s&username=%s&password=%s%s";
        url = String.format(url, LOGIN_URL, clientId, clientSecret, username, password, securityCode);

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = HttpClients.createDefault().execute(httpGet);
        tokenInfo = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));

        logger.info("token信息：" + tokenInfo);
        cacheApi.put("tokenInfo", tokenInfo);
        String token = tokenInfo.getString("access_token");
        return token;
    }
}
